package com.example.farmer.Activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.farmer.Adapter.Product.ChatAdapter;
import com.example.farmer.Database.ChatMessageDatabase;
import com.example.farmer.Database.ProductPublishDatabase;
import com.example.farmer.Entity.ChatMessage;
import com.example.farmer.Entity.ProductPost;
import com.example.farmer.Entity.User;
import com.example.farmer.R;

import java.util.ArrayList;
import java.util.List;

public class CustomerServiceActivity extends AppCompatActivity {

    private static final String PRODUCT_ID = "PRODUCT_ID";
    private int productId;
    private String customerServicePhone;
    private ProductPublishDatabase productPublishDatabase;
    private ChatMessageDatabase chatMessageDatabase;
    private ProductPost productPost;
    private ImageButton back;
    private ImageView productImage;
    private TextView productPrice;
    private TextView shipAddress;
    private TextView contactServiceButton;
    private RecyclerView recyclerViewChat;
    private EditText editTextMessage;
    private Button buttonSend;
    private ChatAdapter chatAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_service);

        initializeViews();
        initializeDatabase();
        loadProductDetails();
        setupChatAdapter();
        setupClickListeners();
    }

    private void initializeViews() {
        productId = getIntent().getIntExtra(PRODUCT_ID, -1);
        customerServicePhone = getIntent().getStringExtra("CUSTOMER_SERVICE_PHONE");
        // 可能需要将客服电话显示在界面上或用于拨打电话的功能

        back = findViewById(R.id.back_button);
        productImage = findViewById(R.id.product_image);
        productPrice = findViewById(R.id.product_price);
        shipAddress = findViewById(R.id.ship_address);
        contactServiceButton = findViewById(R.id.contact_service_button);
        recyclerViewChat = findViewById(R.id.recyclerViewChat);
        editTextMessage = findViewById(R.id.editTextMessage);
        buttonSend = findViewById(R.id.buttonSend);
    }

    private void initializeDatabase() {
        productPublishDatabase = ProductPublishDatabase.getInstance(this);
    }

    private void loadProductDetails() {
        productPost = productPublishDatabase.getProductPostById(productId);
        if (productPost != null) {
            Glide.with(this)
                    .load(productPost.getImageUri())
                    .into(productImage);
            productPrice.setText(String.format("¥%s", productPost.getPrices()));
            shipAddress.setText("发货地址: " + productPost.getShipaddress());
        }
    }

    private void setupChatAdapter() {
        // 初始化数据库帮助类
        chatMessageDatabase = new ChatMessageDatabase(this);

        // 从数据库加载聊天消息
        List<ChatMessage> chatMessages = chatMessageDatabase.loadChatMessagesFromDatabase(productId);

        // 检查 chatMessages 是否为 null 或空
        if (chatMessages != null && !chatMessages.isEmpty()) {
            // 使用加载的消息列表初始化聊天适配器
            chatAdapter = new ChatAdapter(chatMessages);
        } else {
            // 如果没有消息，也可以创建一个空的适配器实例
            chatAdapter = new ChatAdapter(new ArrayList<>());
        }

        recyclerViewChat.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewChat.setAdapter(chatAdapter);
    }

    private void setupClickListeners() {
        back.setOnClickListener(view -> finish());
        contactServiceButton.setOnClickListener(view -> showToast("请联系客服"));
        buttonSend.setOnClickListener(view -> sendMessage());
    }

    private void sendMessage() {
        String messageContent = editTextMessage.getText().toString();
        if (!messageContent.isEmpty()) {

            SharedPreferences sharedPreferences = getSharedPreferences("loginNumber" , Context.MODE_PRIVATE);
            String userNumber = sharedPreferences.getString("userNumber", "");

            // 创建一个新的 ChatMessage 实例
            ChatMessage newMessage = new ChatMessage(productId,userNumber,customerServicePhone, messageContent, System.currentTimeMillis(),false);

            // 将消息保存到数据库
            long newRowId = chatMessageDatabase.insertChatMessage(newMessage);
            if (newRowId != -1) {
                // 如果消息保存成功，将其添加到聊天适配器中
                chatAdapter.addMessage(newMessage);
            } else {
                // 保存消息到数据库失败的处理
                showToast("发送消息失败");
            }

            // 清空输入框
            editTextMessage.setText("");
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}